package com.design.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.design.reggie.common.Result;
import com.design.reggie.entity.Category;
import com.design.reggie.service.CategoryService;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {


    @Autowired
    private CategoryService categoryService;

    /**
     * 添加分类
     * @param category
     * @return
     */
    @PostMapping
    public Result<String> save(@RequestBody Category category) {
        categoryService.save(category);
        return Result.success("新增分类成功");
    }

    /**
     * 分类管理分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public Result<Page<Category>> page(int page, int pageSize) {
        // 分页构造器
        Page<Category> pageInfo = new Page<>(page, pageSize);
        // 查询条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Category::getSort);

        // 执行分页查询
        categoryService.page(pageInfo, queryWrapper);

        return Result.success(pageInfo);
    }

    /**
     * 修改分类
     * @param category
     * @return
     */
    @PutMapping
    public Result<String> update(@RequestBody Category category) {
        categoryService.updateById(category);
        return Result.success("分类修改成功");
    }

    /**
     * 删除分类
     * @param id 分类id
     *           http://localhost:8080/category?id=1619946687276883969 这种url的请求 @RequestParam注解可以省略
     * @return
     */
    @DeleteMapping
    public Result<String> delete(@RequestParam long id) {
//        categoryService.removeById(id);
        categoryService.remove(id);
        return Result.success("分类删除成功");
    }

    /**
     * 根据条件查询分类
     * 这边实际上可以只传一个type参数
     * 此处是将type作为属性传递给了Category
     * @param category
     * @return
     */
    @GetMapping("/list")
    public Result<List<Category>> getList(Category category) {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        // 根据Category的type判断是菜品分类还是套餐分类
        queryWrapper.eq(category.getType() != null, Category::getType, category.getType());
        // 排序条件
        queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> categories = categoryService.list(queryWrapper);
        return Result.success(categories);
    }

}
